// 1,导入expresss对象
const express = require('express')
const { getAll, getOne, exec } = require('../db')
// 2，创建router对象,express.Router()中的Router首字母必须大写，否则报错
const router = express.Router()
// 3，编写接口
// 获取所有公告
router.get('/', async function (req, res, next) {
  //操作数据库
  let sql = `select * from gg_notice`
  const data = await getAll(sql)
  res.send({
    code: 0,
    message: '获取所用公告成功',
    result: data,
  })
})
// 根据id获取单个公告
router.get('/:notice_id', async function (req, res, next) {
  const { notice_id } = req.params
  // 操作数据库
  let sql = `select * from gg_notice where notice_id=${notice_id}`
  const data = await getOne(sql)
  console.log(data)
  res.send({
    code: 0,
    message: '获取公告成功',
    result: {
      id: data.notice_id,
      content: data.notice_content,
      time: data.notice_time,
    },
  })
})

// 添加公告
router.post('/', async function (req, res, next) {
  const { notice_content, user_id } = req.body
  // 操作数据库
  let sql = `insert into gg_notice(notice_content,user_id) values('${notice_content}','${user_id}')`
  const data = await exec(sql)
  console.log(data);
  res.send({
    code: 0,
    message: '添加公告成功',
    result: {
      id: data.insertId,
      content: notice_content,
    },
  })
})

// 删除公告
router.delete('/:notice_id', async function (req, res) {
  const { notice_id } = req.params
  //操作数据库
  let sql = `delete from gg_notice where notice_id = ${notice_id}`
  const data = await exec(sql)
  res.send({
    code: 0,
    message: '删除公告成功',
  })
})

module.exports = router
